<template>
  <div class="patient-vitals-panel">
    <!-- 顶部标题栏 -->
    <div class="panel-header">
      <div class="title-section">
        <el-icon class="title-icon"><Monitor /></el-icon>
        <h2>我的生命体征</h2>
      </div>
      <div class="time-range">
        <el-date-picker
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            @change="loadVitalData"
        />
      </div>
    </div>

    <!-- 健康状态概览 -->
    <div class="health-status">
      <el-alert
          :title="healthStatus.title"
          :type="healthStatus.type"
          :closable="false"
          show-icon
      >
        <template #default>
          <p>{{ healthStatus.message }}</p>
          <p v-if="healthStatus.suggestion" class="suggestion">{{ healthStatus.suggestion }}</p>
        </template>
      </el-alert>
    </div>

    <!-- 实时数据卡片 -->
    <div class="vital-cards">
      <el-card
          v-for="item in vitalCards"
          :key="item.key"
          class="vital-card"
          :class="{'abnormal': item.isAbnormal}"
      >
        <div class="card-content">
          <div class="card-icon" :style="{color: item.color}">
            <el-icon><component :is="item.icon" /></el-icon>
          </div>
          <div class="card-text">
            <h3>{{ item.value }} <small>{{ item.unit }}</small></h3>
            <p>{{ item.label }}</p>
            <p v-if="item.trend" class="trend">
              <el-icon :class="item.trend"><CaretTop v-if="item.trend === 'up'" /><CaretBottom v-else /></el-icon>
              {{ item.trendText }}
            </p>
            <p v-if="item.isAbnormal" class="warning">
              <el-icon><Warning /></el-icon>
              超出正常范围
            </p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 趋势图表 -->
    <div class="chart-section">
      <el-tabs v-model="activeChart" class="chart-tabs">
        <el-tab-pane label="体温趋势" name="temperature">
          <line-chart :data="chartData.temperature" :range="normalRanges.temperature" />
        </el-tab-pane>
        <el-tab-pane label="心率趋势" name="pulse">
          <line-chart :data="chartData.pulse" :range="normalRanges.pulse" />
        </el-tab-pane>
        <el-tab-pane label="血压趋势" name="bloodPressure">
          <dual-line-chart
              :data="chartData.bloodPressure"
              :ranges="[normalRanges.bloodPressure.systolic, normalRanges.bloodPressure.diastolic]"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 历史记录表格 -->
    <div class="history-section">
      <h3 class="section-title">历史记录</h3>
      <el-table :data="historyData" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="temperature" label="体温(℃)" width="100" />
        <el-table-column prop="pulse" label="心率(bpm)" width="100" />
        <el-table-column label="血压(mmHg)" width="120">
          <template #default="{row}">
            {{ row.bloodPressure.systolic }}/{{ row.bloodPressure.diastolic }}
          </template>
        </el-table-column>
        <el-table-column prop="oxygenSaturation" label="血氧(%)" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="getStatusType(row)" size="small">
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Monitor, CaretTop, CaretBottom, Warning } from '@element-plus/icons-vue'

// 正常范围参考值
const normalRanges = {
  temperature: { min: 36.0, max: 37.2 },
  pulse: { min: 60, max: 100 },
  bloodPressure: {
    systolic: { min: 90, max: 140 },
    diastolic: { min: 60, max: 90 }
  },
  oxygenSaturation: { min: 95, max: 100 }
}

// 当前生命体征数据
const currentData = reactive({
  temperature: 36.5,
  pulse: 72,
  bloodPressure: { systolic: 120, diastolic: 80 },
  oxygenSaturation: 98,
  lastUpdated: '2023-05-15 08:30'
})

// 图表数据
const chartData = reactive({
  temperature: generateChartData(36, 37.5, 7),
  pulse: generateChartData(60, 100, 7),
  bloodPressure: {
    systolic: generateChartData(110, 130, 7),
    diastolic: generateChartData(70, 90, 7)
  }
})

// 历史记录数据
const historyData = reactive(generateHistoryData(14))

const timeRange = ref([])
const activeChart = ref('temperature')

// 计算健康状态
const healthStatus = computed(() => {
  const abnormalCount = vitalCards.value.filter(card => card.isAbnormal).length

  if (abnormalCount >= 2) {
    return {
      title: '健康状况异常',
      type: 'error',
      message: '您有多项生命体征超出正常范围',
      suggestion: '建议尽快联系医生进行咨询'
    }
  } else if (abnormalCount === 1) {
    return {
      title: '健康状况注意',
      type: 'warning',
      message: '您有一项生命体征超出正常范围',
      suggestion: '请关注变化趋势，如有不适请咨询医生'
    }
  } else {
    return {
      title: '健康状况良好',
      type: 'success',
      message: '您的各项生命体征均在正常范围内'
    }
  }
})

// 生命体征卡片数据
const vitalCards = computed(() => [
  {
    key: 'temp',
    label: '体温',
    value: currentData.temperature.toFixed(1),
    unit: '℃',
    icon: 'Sunny',
    color: '#FF6B6B',
    isAbnormal: currentData.temperature < normalRanges.temperature.min ||
        currentData.temperature > normalRanges.temperature.max,
    trend: getTrend(chartData.temperature),
    trendText: getTrendText(chartData.temperature, '体温')
  },
  {
    key: 'pulse',
    label: '心率',
    value: currentData.pulse,
    unit: 'bpm',
    icon: 'Connection',
    color: '#4ECDC4',
    isAbnormal: currentData.pulse < normalRanges.pulse.min ||
        currentData.pulse > normalRanges.pulse.max,
    trend: getTrend(chartData.pulse),
    trendText: getTrendText(chartData.pulse, '心率')
  },
  {
    key: 'bp',
    label: '血压',
    value: `${currentData.bloodPressure.systolic}/${currentData.bloodPressure.diastolic}`,
    unit: 'mmHg',
    icon: 'TrendCharts',
    color: '#45B7D1',
    isAbnormal: currentData.bloodPressure.systolic < normalRanges.bloodPressure.systolic.min ||
        currentData.bloodPressure.systolic > normalRanges.bloodPressure.systolic.max ||
        currentData.bloodPressure.diastolic < normalRanges.bloodPressure.diastolic.min ||
        currentData.bloodPressure.diastolic > normalRanges.bloodPressure.diastolic.max
  },
  {
    key: 'oxygen',
    label: '血氧',
    value: currentData.oxygenSaturation,
    unit: '%',
    icon: 'Opportunity',
    color: '#A78BFA',
    isAbnormal: currentData.oxygenSaturation < normalRanges.oxygenSaturation.min
  }
])

// 辅助函数
function generateChartData(min, max, days) {
  return Array.from({ length: days }, (_, i) => ({
    date: new Date(Date.now() - (days - i - 1) * 86400000).toLocaleDateString(),
    value: min + Math.random() * (max - min)
  }))
}

function generateHistoryData(count) {
  return Array.from({ length: count }, (_, i) => {
    const date = new Date(Date.now() - (count - i - 1) * 86400000)
    const temp = 36 + Math.random() * 1.5
    const pulse = 60 + Math.random() * 40
    const systolic = 90 + Math.random() * 50
    const diastolic = 60 + Math.random() * 30
    const oxygen = 95 + Math.random() * 5

    return {
      date: date.toLocaleDateString(),
      temperature: temp.toFixed(1),
      pulse: Math.round(pulse),
      bloodPressure: {
        systolic: Math.round(systolic),
        diastolic: Math.round(diastolic)
      },
      oxygenSaturation: Math.round(oxygen),
      isNormal: temp >= 36 && temp <= 37.2 &&
          pulse >= 60 && pulse <= 100 &&
          systolic >= 90 && systolic <= 140 &&
          diastolic >= 60 && diastolic <= 90 &&
          oxygen >= 95
    }
  })
}

function getTrend(data) {
  if (data.length < 2) return null
  const last = data[data.length - 1].value
  const prev = data[data.length - 2].value
  return last > prev ? 'up' : last < prev ? 'down' : null
}

function getTrendText(data, name) {
  const trend = getTrend(data)
  if (!trend) return `${name}稳定`
  return trend === 'up' ? `${name}上升` : `${name}下降`
}

function getStatusType(row) {
  return row.isNormal ? 'success' : 'danger'
}

function getStatusText(row) {
  return row.isNormal ? '正常' : '异常'
}

function loadVitalData() {
  // 这里应该是API调用获取数据
  console.log('加载数据:', timeRange.value)
}
</script>

<style scoped>
.patient-vitals-panel {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
}

.title-icon {
  font-size: 28px;
  margin-right: 10px;
  color: #409EFF;
}

.health-status {
  margin-bottom: 20px;
}

.suggestion {
  margin-top: 8px;
  font-size: 14px;
}

.vital-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.vital-card {
  transition: all 0.3s;
}

.vital-card.abnormal {
  border-left: 4px solid #F56C6C;
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
}

.card-icon {
  font-size: 36px;
}

.card-text h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.card-text p {
  margin: 4px 0 0;
  color: #666;
}

.trend {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.trend.up {
  color: #F56C6C;
}

.trend.down {
  color: #67C23A;
}

.warning {
  color: #F56C6C;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.chart-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 20px 0 15px;
  font-size: 18px;
  color: #333;
}

@media (max-width: 768px) {
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .vital-cards {
    grid-template-columns: 1fr;
  }
}
</style>
